package com.zx.handler;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.zx.model.ConfContent;

/**
 * @Title: ReadNgnixCofUtil
 * @Description: 读取配置文件，生成简单对象
 * @author: xue.zhang
 * @date: 2018年7月31日下午5:23:16
 * @company: alibaba
 * @Copyright: Copyright (c) 2017
 * @version v1.0
 */
public abstract class ReadNgnixCofUtil {
	/**
	 * 方法入口
	 * @param file
	 * @author: xue.zhang
	 * @date 2018年7月31日下午5:30:22
	 */
	public static List<ConfContent> readNgnixConfig(File file){
        BufferedReader br = null ;
        StringBuffer sb = new StringBuffer();// 将读取的配置转为一行，方便处理
        try{
            br = new BufferedReader(new FileReader(file)) ;
            String tmp = null ;
            while((tmp = br.readLine()) != null){
            	tmp = readLine(tmp);
            	if(tmp.length() > 0)
            		sb.append(tmp);
            }
            return  format(sb.toString());
        } catch (IOException e) {
            e.printStackTrace() ;
        } finally {
        	if(br != null) {
        		try {
        			br.close() ;
        		} catch (IOException e) {
        			e.printStackTrace();
        		}
        	}
        }
        return null;
    }
	/**
	 * 读取一行，去除注释
	 * @param line
	 * @return
	 * @author: xue.zhang
	 * @date 2018年7月31日下午5:29:43
	 */
	private static String readLine(String line) {
		int commentIndexOf = line.indexOf("#");
		return commentIndexOf >= 0 ? line.substring(0, commentIndexOf).trim() :  line.trim();
	}
	/**
	 * 开始数据类型转换
	 * @param content
	 * @return
	 * @author: xue.zhang
	 * @date 2018年7月31日下午5:30:08
	 */
	private static List<ConfContent> format(String content) {
		List<ConfContent> confList = new ArrayList<>();
		String temp = content.trim();
		
		while(temp != null && temp.length() > 0) {
			int endIndexOf = temp.indexOf(";");
			int childIndexOf = temp.indexOf("{");
			
			if(endIndexOf == -1 && childIndexOf == -1) {// 1. 没有找到结束符，也没找到子配置，异常情况
				throw new RuntimeException("配置文件异常:" + temp);
			}
			
			endIndexOf = endIndexOf == -1 ? 9999999 : endIndexOf;
			childIndexOf = childIndexOf == -1 ? 9999999 : childIndexOf;
			
			if(endIndexOf < childIndexOf) {//只有结束符
				String oneConf = temp.substring(0, endIndexOf);//获得一条配置
				confList.add(parseContent(oneConf));
				temp = temp.substring(Math.min(endIndexOf + 1, temp.length()));
			}
			
			if(endIndexOf > childIndexOf) {//只有子配置
				int childEndIndex = getChildContentIndex(temp);
				
				String childConf = temp.substring(0, childEndIndex + 1);//获得一条配置,比如:    http { name value;}
				temp = temp.substring(Math.min(childEndIndex + 1, temp.length()));
				
				int index = childConf.indexOf("{");
				String name = childConf.substring(0, index).trim();
				String childContent = childConf.substring(index + 1, childConf.length() - 1).trim();
				ConfContent hashChildConf = new ConfContent();
				hashChildConf.setConfName(name);
				// 递归生成子配置
				List<ConfContent> format = format(childContent);
				hashChildConf.setChildContent(format);
				
				confList.add(hashChildConf);
			}
		}
		return confList;
	}
	
	/**
	 * 获得一行配置，不包括子配置
	 * @param oneConf
	 * @author: xue.zhang
	 * @date 2018年7月31日上午10:58:09
	 */
	private static ConfContent parseContent(String oneConf) {
		int delimiter = oneConf.indexOf(" ");//先把内容分成两个部分
		if(delimiter <= 0) {
			throw new RuntimeException("配置文件异常:" + oneConf);
		}
		String key = oneConf.substring(0, delimiter).trim();
		String value = oneConf.substring(delimiter).trim();

		ConfContent confContent = new ConfContent();
		confContent.setConfName(key);
		confContent.setConfValue(value);
		
		return confContent;
	}
	/**
	 * 获得一个子配置结束的位置
	 * @param content
	 * @return
	 * @author: xue.zhang
	 * @date 2018年7月31日下午5:29:26
	 */
	private static int getChildContentIndex(String content) {
		if(content == null || content.length() == 0) {
			throw new RuntimeException("配置文件异常:" + content); 
		}
		int childEndIndex = 0;
		int childIndexOf = content.indexOf("{");
		
		int index = 1;
		char[] charArray = content.toCharArray();
		for (int i = childIndexOf + 1; i < charArray.length; i++) {
			if(charArray[i] == '{') {
				index++;
			} else if(charArray[i] == '}') {
				index--;
			}
			if(index == 0) {
				childEndIndex = i;
				break;
			}
		}
		
		if(childEndIndex == 0) {
			throw new RuntimeException("配置文件异常:" + content); 
		}
		
		return childEndIndex;
	}

}
